package com.cecj03.papago.controller.crud;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class PhotoServlet
 */
@WebServlet("/PhotoServlet.view")
public class PhotoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
  
	
    public PhotoServlet() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String photoid = request.getParameter("photoid");
		
		byte[] photo = null;
		if(photoid!=null && photoid.trim().length()!=0) {
			photo = this.readDetailTable(photoid);
		}
		if(photo==null || photo.length==0) {
			
		}
		response.setContentType("image/jpeg");
		OutputStream out = response.getOutputStream();
		out.write(photo);
		out.close();
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
	private byte[] readDetailTable(String photoid) {
		byte[] result = null;
		
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rset = null;
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/xxx");
			
			conn = ds.getConnection();
			stmt = conn.prepareStatement(
					"select memPic from PapaMem where memId =?");
			stmt.setString(1, photoid);
			rset = stmt.executeQuery();
			if(rset.next()) {
				result = rset.getBytes("memPic");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rset!=null) {
				try {
					rset.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (stmt!=null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

}
